package Day012_多线程2.demo03_并发包;

import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author zhangyan
 * @date 2020/4/30 11:09
 */
public class demo02_CopyOnWriteArraySet {
    public static void main(String[] args) throws InterruptedException {

        //创建对象
        MyRunnable1 mr1 = new MyRunnable1();
        //创建线程
        Thread t1 = new Thread(mr1);
        t1.start();

        Thread.sleep(2000);

        for (int i = 10001; i <= 20000; i++) {
            mr1.set1.add(i);
        }
        System.out.println("集合最终元素个数:" + mr1.set1.size());
        System.out.println(mr1.set1); // 1-10000无序
    }
}
/*
    元素个数应该是1000个,但实际结果可能会大于1000 (元素唯一)

    线程1,添加0-999,  线程2,添加0-999,元素是重复的.

    线程1添加0,先判断是否存在,不存在,但是此时线程2同样判断是否存在0,不存在,
    线程1添加0,计数器+1, 线程2添加0,计数器+1,
    set集合去重,只有一个0 ,但是计数器==2

    所以: 集合有1000个元素,但是size获取到的>=1000
 */


class MyRunnable1 implements Runnable{
    //HashSet<Integer> set = new HashSet<>();
    CopyOnWriteArraySet<Integer> set1 = new CopyOnWriteArraySet<>();

    @Override
    public void run() {
        for (int i = 1; i <= 10000; i++) {
            set1.add(i);
        }
        System.out.println("添加完毕");
    }
}
